package com.sync.utils;

import java.io.IOException;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtobufIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
 

/**
 * Protostuff序列化
 * @author Mark Hsiu
 *
 */
public class ProtostuffCodec implements SerializeCodec<Message>{
	
	//缓存buff 大小,最好灵活控制，稍微影响效率
	private static final int BUFFER = 4*1024;
	
	private static final SerializeCodec<Message> codec = new ProtostuffCodec();
	
 	public static SerializeCodec<Message> OneInstance(){
		return codec;
	}
 	
	
	@Override
	public byte[] serialize(Message message) throws IOException {
		if(message == null ) {
            throw new RuntimeException();
        }
       
		Schema<Message> schema =  RuntimeSchema.getSchema(Message.class);
        // 缓存buff  
        LinkedBuffer buffer = LinkedBuffer.allocate(BUFFER);  
        // 序列化成protobuf的二进制数据  
        byte[] data = ProtobufIOUtil.toByteArray(message, schema, buffer);  
        return data;
	}

	@Override
	public Message deserialize(byte[] data) throws IOException {
		Message message = new Message();
 
		Schema<Message> schema =  RuntimeSchema.getSchema(Message.class);
		ProtobufIOUtil.mergeFrom(data, message, schema); 
		return message;
	}

}
